#region Using References

using System;
using System.Reactive.Concurrency;
using System.Reactive.Linq;
using System.Threading.Tasks;

#endregion

namespace Beaker.Services.Tasks.Tpl
{
	/// <summary>
	/// Task service that uses the Task-Parallel-Library (TPL)
	/// to schedule the task over threads a
	/// </summary>
	public sealed class TplTaskService
		: TaskService
	{
		/// <summary>
		/// Creates a collection that will group multiple tasks together
		/// </summary>
		/// <typeparam name="T">The type of the results that the takss in the colletion will return</typeparam>
		/// <returns>
		/// The collection to add tasks on
		/// </returns>
		public override ITaskCollection<T> CreateCollection<T>()
		{
			return new TplTaskCollection<T>();
		}

		/// <summary>
		/// Start the given task
		/// </summary>
		/// <param name="action">The action executing the task</param>
		/// <returns>The task started</returns>
		public override Task Execute( Action action )
		{
			var task = new Task( action );
			task.Start();
			return task;
		}

		/// <summary>
		/// Starts the given task and expects a result
		/// </summary>
		/// <typeparam name="T">The type of the result</typeparam>
		/// <param name="func">The function executing the task and returning the result</param>
		/// <returns></returns>
		public override Task<T> Execute<T>( Func<T> func )
		{
			var task = new Task<T>( func );
			task.Start();
			return task;
		}

		public override IObservable<T> Observe<T>( Func<System.Collections.Generic.IEnumerable<T>> func )
		{
			return func().ToObservable( TaskPoolScheduler.Default );
		}
	}
}